#include<iostream>
#include<sstream>
#include<cstring>
using namespace std;
const int N = 510;
int n, m;
bool g[N][N];
int dis[N];
int stop[N];
int q[N];
void bfs()
{
	memset(dis, 0x3f, sizeof(dis));
	dis[1] = 0;
	int hh = 0, tt = 0;
	q[0] = 1;
	while (hh <= tt) {
		int t = q[hh++];
		for (int i = 1; i <= n; i++) {
			if (g[t][i] && dis[i] > dis[t] + 1) {
				dis[i] = dis[t] + 1;
				q[++tt] = i;
			}
		}
	}
}
int main()
{
	cin >> m >> n;
	string line;
	getline(cin, line);
	while (m--) {
		int cnt = 0;
		int p;
		//memset(stop, 0, sizeof(stop));
		getline(cin, line);
		stringstream ss(line);
		while (ss >> p) {
			stop[cnt++] = p;
		}
		for (int i = 0; i < cnt; i++) {
			for (int j = i + 1; j < cnt; j++) {
				g[stop[i]][stop[j]] = 1;
			}
		}
	}
	bfs();
	if (dis[n] == 0x3f3f3f3f) {
		cout << "N0" << endl;
	}
	else {
		cout << max(0, dis[n] - 1) << endl;
	}
	return 0;
}